package model

import (
	"fmt"
	"log"
	"my-go-project/config"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

var DB *gorm.DB

func ConnectDatabase() {
	dsn := config.AppConfig.Database.User + ":" + config.AppConfig.Database.Password + "@tcp(" + config.AppConfig.Database.Host + ":" + config.AppConfig.Database.Port + ")/" + config.AppConfig.Database.Name + "?charset=utf8mb4&parseTime=true"
	var err error
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			// 禁用字段自动转为 snake_case
			SingularTable: true, // 保证表名是单数形式
			NoLowerCase:   true,
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	sqlDB, _ := DB.DB()
	sqlDB.SetMaxOpenConns(config.AppConfig.Database.MaxOpenConns)
	sqlDB.SetMaxIdleConns(config.AppConfig.Database.MaxIdleConns)
	sqlDB.SetConnMaxLifetime(time.Hour)

	if err := sqlDB.Ping(); err != nil {
		log.Fatal(err)
	}
	fmt.Println("成功连接到 MySQL 数据库!")

	// 1. 先迁移基本表
	DB.AutoMigrate(&User{})
	DB.AutoMigrate(&Passage{})

	// 2. 然后迁移依赖这些表的表
	DB.AutoMigrate(&Follow{})
	DB.AutoMigrate(&PassageLike{})
	DB.AutoMigrate(&Message{})
	DB.AutoMigrate(&Comment{})
	DB.AutoMigrate(&Adopt{})

	// 3. 最后迁移关联表
	DB.AutoMigrate(&CommentLike{})
	DB.AutoMigrate(&AdoptComment{})

	// 4. 手动添加comment和message的外键关联
	DB.Exec("ALTER TABLE Comment ADD CONSTRAINT fk_Comment_Passage FOREIGN KEY (PassageID) REFERENCES Passage(PassageID)")
	DB.Exec("ALTER TABLE Message ADD CONSTRAINT fk_Message_Passage FOREIGN KEY (PassageID) REFERENCES Passage(PassageID)")
	DB.Exec("ALTER TABLE Adopt ADD CONSTRAINT fk_Adopt_Passage FOREIGN KEY (PassageID) REFERENCES Passage(PassageID)")
}
